package com.jhy.review.paixu;

import java.util.Arrays;

/**
 * @author go_jhy
 * @create 2022/5/18 - 下午 6:16
 * 归并排序
 */
@SuppressWarnings("all")
public class GuiBing {

    public static void mergeSort(int arr[]) {
        if(arr == null || arr.length<2){
            return;
        }
        process(arr,0,arr.length-1);

    }
    public static void process(int[] arr,int L,int R) {
        if(L == R) {
            return;
        }
        //右移是除以2的原因
        int mid = L+((R - L) >> 1);
        //左边排序
        process(arr, L, mid);
        System.out.println("前面"+Arrays.toString(arr));
        //右边排序
        process(arr,mid+1,R);
        System.out.println("后面"+Arrays.toString(arr));
        //合并
        merge(arr,L,mid,R);
    }

    public static void merge(int[] arr,int L,int M,int R){
        //先定义一个临时空间
        int[] help = new int[R - L + 1];
        int i = 0;
        int p1 = L;
        int p2 = M+1;
        while (p1 <= M && p2 <= R){
            help[i++] = arr[p1]<=arr[p2] ? arr[p1++] : arr[p2++];
        }
        while(p1 <= M){
            help[i++] = arr[p1++];
        }
        while(p2 <= R){
            help[i++] = arr[p2++];
        }
        for(int j = 0;j<help.length;j++){
            arr[j+L] = help[j];
        }


    }


}
